package org.example.interceptors;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.util.JWTUtils;
import org.example.util.ResponseData;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

public class LoginTokenInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        //前置处理

        //获取前端的传过来的token
        String token = httpServletRequest.getHeader("token");

        if(token == null || token.equals("") || token.equals("null")){
            //用户没有登录
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json;charset=utf-8");

            //封装一个ResponseData转换的json格式对象
            ObjectMapper objectMapper = new ObjectMapper();
            //把一个对象转换为json格式字符串
            String jsonResult = objectMapper.writeValueAsString(ResponseData.error("没有登录",101));

            httpServletResponse.getWriter().write(jsonResult);
            return false;

        }else{

            //验证token的合法性
            boolean result =  JWTUtils.verifier(token);
            if(!result){
                //用户每天通过验证
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json;charset=utf-8");

                //封装一个ResponseData转换的json格式对象
                ObjectMapper objectMapper = new ObjectMapper();
                //把一个对象转换为json格式字符串
                String jsonResult = objectMapper.writeValueAsString(ResponseData.error("验证失败，请重新登录",102));

                httpServletResponse.getWriter().write(jsonResult);
                return false;
            }

        }

        return true;

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
